package com.ldd.malphite.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Slf4j

public class TestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        log.error("TestInterceptor cookies : "+cookies.toString());
        HttpSession session = request.getSession();
        log.error("TestInterceptor session : " + session.toString());
        String requestURI = request.getRequestURI();
        log.error("TestInterceptor requestURI : " + requestURI);
        String requestURL = request.getRequestURL().toString();
        log.error("TestInterceptor requestURL : " + requestURL);
        String method = request.getMethod();
        log.error("TestInterceptor method : " + method);
        String remoteAddr = request.getRemoteAddr();
        log.error("TestInterceptor remoteAddr : " +remoteAddr);
        String remoteHost = request.getRemoteHost();
        log.error("TestInterceptor remoteHost : " +remoteHost);
        String remoteUser = request.getRemoteUser();
        log.error("TestInterceptor remoteUser : " + remoteUser);

        //设置返回类型和编码，否则会乱码
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("<h1 style='color:red'>没有访问权限！</h1>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
